var http = require('http');
var fs = require('fs');
var cheerio = require('cheerio');
var request = require('request');
var i = 0;
var url = "http://gaokao.chsi.com.cn/zsgs/zzxblqzgmd--method-listStu,ssdm-11,yxdm-10005,year-2017,zslx=1.dhtml"; 
           
           
//初始url 

function fetchPage(x) {     //封装了一层函数
    startRequest(x); 
}


function startRequest(x) {
     //采用http模块向服务器发起一次get请求      
    http.get(x, function (res) {     
        var html = '';        //用来存储请求网页的整个html内容
        var detail = [];        
        res.setEncoding('utf-8'); //防止中文乱码
     //监听data事件，每次取一块数据
        res.on('data', function (chunk) {   
            html += chunk;
            
        });
        
     //监听end事件，如果整个网页内容的html都获取完毕，就执行回调函数
        res.on('end', function () {
               console.log(html);
                var $ = cheerio.load(html); //采用cheerio模块解析html
                //console.log(html);

               // detail = $('#YKTabCon2_10 tbody tr').text().trim();
                // var detail = $('#YKTabCon2_10 tbody tr td').next().text().trim();

                //打印详细信息
				//把多个空格变成一个
				//detail=detail.replace(/\s+/g,'    ');
				
				//console.log(detail); 

                savedContent($,html);
        });

    }).on('error', function (err) {
        console.log(err);
    });

}
     //在本地存储所爬取的学生内容
function savedContent($, html) {
	var name = $('.center').text().trim();
	console.log(name);

    var diqu=$('#YKTabCon2_10 tbody tr td:nth-child(3)').text().substring(4, 6);
    console.log(diqu);

	fs.appendFile('./data/' + name +'('+ diqu +')'+ '.html', html, 'utf-8', function (err) {
			if (err) {
				console.log(err);
            }
            else{
                console.log("写成功了");
            }
	});
        
}
fetchPage(url);      